package com.chinatsp.onlineapp.service;

import tsp.cn.http.tools.LogUtil;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.chinatsp.onlineapp.base.Constant;

/**
 * 定位服务类
 */
public class LocationService extends Service implements LocationListener {

	private static final String TAG = "LocationSvc";
	private LocationManager locationManager;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		
     	LogUtil.d( "LocationService onCreate");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		if (locationManager.getProvider(LocationManager.NETWORK_PROVIDER) != null){
			locationManager.requestLocationUpdates(
					LocationManager.NETWORK_PROVIDER, 500, 0, this);
			LogUtil.d( "LocationService onStart NETWORK_PROVIDER");
		}
		else if (locationManager.getProvider(LocationManager.GPS_PROVIDER) != null){
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 500, 0, this);
			
			LogUtil.d( "LocationService onStart GPS_PROVIDER");
		}else{
			LogUtil.d( "无法定位");
		}
	}

	@Override
	public boolean stopService(Intent name) {
		return super.stopService(name);
	}

	int i = 0;
	@Override
	public void onLocationChanged(Location location) {
		
     	LogUtil.d( "Get the current position \n" + location);

		// 通知Activity
		Intent intent = new Intent();
		intent.setAction(Constant.LOCATION_ACTION);
		intent.putExtra(Constant.LOCATION_LATITUDE,
				String.valueOf(location.getLatitude()));
		intent.putExtra(Constant.LOCATION_LONGITUDE,
				String.valueOf(location.getLongitude()));
		sendBroadcast(intent);
		// 如果只是需要定位一次，这里就移除监听，停掉服务。如果要进行实时定位，可以在退出应用或者其他时刻停掉定位服务。
//		locationManager.removeUpdates(this);
//		stopSelf();
	}

	@Override
	public void onProviderDisabled(String provider) {
	}

	@Override
	public void onProviderEnabled(String provider) {
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		
		LogUtil.d( "onStatusChanged provider " + provider);
	}

}
